<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>注册页</title>
		<style>
			.error-msg {
		    color: red;
		  }
		</style>
	</head>
	<body>
		<h2>注册页</h2>
		<form id="registration-form" onsubmit="return check()">
			<div>
				<label for="username">用户名：</label>
				<input type="text" id="username" onchange="validateUsername()">
				<span id="username-msg" class="error-msg"></span>
			</div>
			<div>
				<label for="password">密码：</label>
				<input type="password" id="password">
			</div>
			<div>
				<label for="phone">电话号码：</label>
				<input type="text" id="phone" maxlength="11" onkeydown="validatePhoneNumber(event)">
				<span id="phone-msg" class="error-msg"></span>
			</div>
			<button type="submit">注册</button>
		</form>

		<script>
			var usernameInput = document.getElementById('username');
			var usernameMsg = document.getElementById('username-msg');

			function validateUsername() {
				var username = usernameInput.value;
				var regex = /^[a-zA-Z0-9_-]{3,16}$/;
				if (regex.test(username)) {
					usernameMsg.textContent = '用户名符合要求';
				} else {
					usernameMsg.textContent = '用户名只能包含字母、数字、下划线和短横线，长度为3到16位';
				}
			}

			var phoneInput = document.getElementById('phone');
			var phoneMsg = document.getElementById('phone-msg');

			function validatePhoneNumber(event) {
				var key = event.key;
				if (!(key >= '0' && key <= '9') || phoneInput.value.length >= 11) {
					event.preventDefault();
				}
			}

			function check() {
				var username = document.getElementById('username').value;
				var password = document.getElementById('password').value;
				var phone = document.getElementById('phone').value;
				return true;
			}
		</script>
	</body>
</html>
<!--
			练习1
			编写一个注册页
			1. 电话号码框添加键盘事件 onkeydown
				让用户只能输入数字，不能输入非数字 ，且只能输入最高11位数字
			2. 给用户名框添加onchange事件，立即调用正则判断用户名是否符合要求，显示在输入框后面
			3. 给表单添加onsubmit事件，调用check（）对用户名密码等进行判断，
		-->
